<?php

/**
 * $Id: tools_helper.php 39150 2016-01-26 08:24:57Z liangpengfei $
 */
//pid转url
function pid2url($pid, $w = 0, $h = 0) {
    $ci = & get_instance();
    $ci->load->library('CT_Image');
    $img_url = $ci->ct_image->pid2url($pid, $w, $h);
    return $img_url;
}

//手机号星号
function mobile2nick($mobile) {
    return substr($mobile, 0, 3) . '****' . substr($mobile, 7, 11);
}

//轮询加载静态图片、css、js资源文件
static $i = 1;

function resource_url($path) {

    global $i;
    $ci = & get_instance();
    $config = $ci->config->item('image');
    $host = $config['host'];
    $ceil = $i % 3 + 1;
    if (ENVIRONMENT == 'production') {
        $url = str_replace('http://img', 'http://img' . $ceil, $host . '/' . $path);
    } else {
        $url = "http://" . $_SERVER['HTTP_HOST'] . "/" . $path;
    }
    $i++;
    return $url;
}

//获取当前url下action的名字
function get_action_name() {
    $app_path = str_replace($_SERVER['DOCUMENT_ROOT'], '', __FILE__);
    $query_string = str_replace($app_path, '', $_SERVER['REQUEST_URI']);
    $info = explode("/", $query_string);
    return isset($info[2]) ? $info[2] : "";
}

//获取当前url下controller的名字
function get_controller_name() {
    $app_path = str_replace($_SERVER['DOCUMENT_ROOT'], '', __FILE__);
    $query_string = str_replace($app_path, '', $_SERVER['REQUEST_URI']);
    $info = explode("/", $query_string);
    return isset($info[1]) ? $info[1] : "";
}

/**
 * 获取host根域
 * @param string $httpurl
 * @return void|string
 */
function parseHost($httpurl) {

    $httpurl = strtolower(trim($httpurl));
    if (empty($httpurl))
        return;
    $regx1 = '/https?:\/\/(([^\/\?#&]+\.)?([^\/\?#&\.]+\.)(com\.cn|org\.cn|net\.cn|com\.jp|co\.jp|com\.kr|com\.tw|local)(\:[0-9]+)?)\/?/i';
    $regx2 = '/https?:\/\/(([^\/\?#&]+\.)?([^\/\?#&\.]+\.)(cn|com|org|info|us|fr|de|tv|net|cc|biz|hk|jp|kr|name|me|tw|la|local)(\:[0-9]+)?)\/?/i';
    $host = $tophost = '';
    if (preg_match($regx1, $httpurl, $matches)) {
        $host = $matches[1];
    } elseif (preg_match($regx2, $httpurl, $matches)) {
        $host = $matches[1];
    }
    if ($matches) {
        $tophost = $matches[3] . $matches[4];
        $domainLevel = $matches[2] == 'www.' ? 1 : (substr_count($matches[2], '.') + 1);
    } else {
        $tophost = '';
        $domainLevel = 0;
    }
    return $tophost;
}

/**
 * 加密ID号显示
 * @param int $int
 * @return string
 */
function id_encode($int)
{
    $key = pack('H20', '0123456789abcdef0123'); // 10 bytes key

    return skip32_encode($key, $int);
}

/**
 * 解密ID号显示
 * @param int $int
 * @return string
 */
function id_decode($encryptedInt)
{
    $key = pack('H20', '0123456789abcdef0123'); // 10 bytes key
    return skip32_decode($key, $encryptedInt);
}

function skip32_encode($key, $int) {
    //$key = pack('H20', '0123456789abcdef0123'); // 10 bytes key
    $ci = & get_instance();
    $ci->load->library('CT_Skip32cipher');
    $ci->ct_skip32cipher->set_key($key);
    $bin = pack('N', $int);
    $encrypted = $ci->ct_skip32cipher->encrypt($bin);
    list(, $encryptedInt) = unpack('N', $encrypted);
    return $encryptedInt;
}

function skip32_decode($key, $encryptedInt) {
    $ci = & get_instance();
    $ci->load->library('CT_Skip32cipher');
    $ci->ct_skip32cipher->set_key($key);
    $bin = pack('N', $encryptedInt);
    $decrypted = $ci->ct_skip32cipher->decrypt($bin);
    list(, $decryptedInt) = unpack('N', $decrypted);
    return $decryptedInt;
}

/**
 * 密码加密（密文存储）
 * @param string $password
 * @return string
 */
function hash_encrypt($password) {
    $salt = substr($password, 0, 4);
    $hash = base64_encode(sha1($password . $salt, TRUE) . $salt);
    return $hash;
}

/**
 * 发起一个HTTP/HTTPS的请求
 * @param $url 接口的URL
 * @param $params 接口参数   array('content'=>'test', 'format'=>'json');
 * @param $method 请求类型    GET|POST
 * @param $multi 图片信息
 * @param $extheaders 扩展的包头信息
 * @return string
 */
function request_url($url, $params = array(), $method = 'GET', $multi = false, $extheaders = array()) {
    if (!function_exists('curl_init'))
        exit('Need to open the curl extension');
    $method = strtoupper($method);
    $ci = curl_init();
    curl_setopt($ci, CURLOPT_USERAGENT, 'DUOLE CURL');
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ci, CURLOPT_TIMEOUT, 10);
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ci, CURLOPT_HEADER, false);
    $headers = (array) $extheaders;
    switch ($method) {
        case 'POST':
            curl_setopt($ci, CURLOPT_POST, TRUE);
            if (!empty($params)) {
                if ($multi) {
                    foreach ($multi as $key => $file) {
                        $params[$key] = '@' . $file;
                    }
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                    $headers[] = 'Expect: ';
                } else {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, http_build_query($params));
                }
            }
            break;
        case 'DELETE':
        case 'GET':
            $method == 'DELETE' && curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
            if (!empty($params)) {
                $url = $url . (strpos($url, '?') ? '&' : '?')
                        . (is_array($params) ? http_build_query($params) : $params);
            }
            break;
    }

    curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE);
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($headers) {
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ci, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    $response = curl_exec($ci);
    curl_close($ci);

    return $response;
}

//唯一id
function ci_uuid() {
    return md5(uniqid(rand(), true));
}

/**
 * 取得根域名
 * @param type $domain 域名
 * @return string 返回根域名
 */
function get_domain($domain) {
    $re_domain = '';
    $domain_postfix_cn_array = array("com", "net", "org", "gov", "edu", "com.cn", "cn");
    $array_domain = explode(".", $domain);
    $array_num = count($array_domain) - 1;
    if ($array_domain[$array_num] == 'cn') {
        if (in_array($array_domain[$array_num - 1], $domain_postfix_cn_array)) {
            $re_domain = $array_domain[$array_num - 2] . "." . $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
        } else {
            $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
        }
    } else {
        $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
    }
    return $re_domain;
}

if (!function_exists('set_post_value')) {

    function set_post_value($field = '', $default = '') {
        if (FALSE === ($OBJ = & _get_validation_object())) {
            if (!isset($_POST[$field])) {
                return $default;
            }

            return form_prep($_POST[$field], $field);
        }

        return form_prep($OBJ->set_value($field, $default), $field);
    }

}

if (!function_exists('set_get_value')) {

    function set_get_value($field = '', $default = '') {
        $ci = & get_instance();
        return $ci->input->get($field) !== false ? $ci->input->get($field) : $default;
    }

}

if (!function_exists('set_get_post_value')) {

    function set_get_post_value($field = '', $default = '') {
        $ci = & get_instance();
        return $ci->input->get_post($field, true) !== false ? $ci->input->get_post($field, true) : $default;
    }

}


if (!function_exists('get_value')) {

    function get_value($value = '', $default = '') {

        return $value ? $value : $default;
    }

}

//get所有参数
if (!function_exists('set_get_values')) {

    function set_get_values() {
        $ci = & get_instance();
        return $ci->input->get() !== false ? $ci->input->get() : array();
    }

}


if (!function_exists('ci_mrcencode')) {

    //ci加密
    function ci_mrcencode($string) {
        $ci = & get_instance();
        $ci->load->library('encrypt');
        $token = $ci->encrypt->encode($string);
        return base64_encode($token);
    }

}

if (!function_exists('ci_mrcdecode')) {

    //ci解密
    function ci_mrcdecode($token) {
        $ci = & get_instance();
        $ci->load->library('encrypt');
        $token = base64_decode($token);
        $string = $ci->encrypt->decode($token);
        return $string;
    }

}

//根据ip获取城市接口
if (!function_exists('get_ip_city')) {

    function get_ip_city($ip) {
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" . $ip;
        $res = request_url($url);
        $res = json_decode($res, true);
        return isset($res['city']) ? $res['city'] : false;
    }

}

//url二级头
if (!function_exists('url_head')) {

    function url_head($url) {
        $urlinfo = parse_url($url);
        $host = $urlinfo['host'];
        $tmp = explode(".", $host);
        return $tmp[0];
    }

}

if (!function_exists('ci_url')) {

    function ci_url() {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    }

}

//获取距离当前的日期数
if (!function_exists('count_data')) {

    function count_data($date) {
        $d1 = time();
        $d2 = strtotime($date);
        $cha = $d1 - $d2;
        $aa = '';
        if ($cha < 60) {
            $aa = $cha . '秒以前';
        } elseif (60 <= $cha && $cha < 60 * 60) {
            $num = $cha / 60;
            $aa = intval($num) . '分钟前';
        } elseif (60 * 60 <= $cha && $cha < 60 * 60 * 24) {
            $num = $cha / (60 * 60);
            $aa = intval($num) . '小时前';
        } elseif (60 * 60 * 24 <= $cha && $cha < 60 * 60 * 24 * 30) {
            $num = $cha / (60 * 60 * 24);
            $aa = intval($num) . '天前';
        } elseif (60 * 60 * 24 * 30 <= $cha && $cha < 60 * 60 * 24 * 30 * 12) {
            $num = $cha / (60 * 60 * 24 * 30);
            $aa = intval($num) . '个月前';
        } else {
            $num = $cha / (60 * 60 * 24 * 30 * 12);
            $aa = intval($num) . '年前';
        }

        return $aa;
    }

}

/**
 * 获取运营后台的左侧菜单
 * @return mixed
 */
function get_menu_list(){
    $ci = & get_instance();
    $ci->load->library("AdminAction");

    if($ci->adminaction->role_name == '超级管理员'){
        $menu_list = $ci->adminaction->supper_menu_list;
    }else{
        $menu_list = $ci->adminaction->menu_list;
    }
    return $menu_list;
}

/**
 * 获取运营后台的左侧菜单
 * @return mixed
 */
function get_menu_list_nursery(){
    $ci = & get_instance();
    $ci->load->library("NurseryAdminAction");

    if($ci->nurseryadminaction->role_name == '超级管理员'){
        $menu_list = $ci->nurseryadminaction->supper_menu_list;
    }else{
        $menu_list = $ci->nurseryadminaction->menu_list;
    }
    return $menu_list;
}

/**
 * 手机号验证
 *
 * @param  string $mobile
 * @return boolean
 */
function check_mobile($mobile) {
    if (preg_match('/^(13|15|18|17)[0-9]{9}$/i', $mobile)) {
        return true;
    }
    return false;
}

//判断ip地址合法性
function is_ip($ip)
{
    return preg_match("/^([0-9]{1,3}\.){3}[0-9]{1,3}$/", $ip);
}

//获取客户端ip地址
function get_real_ip() {
    $ip = false;
    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('REMOTE_ADDR')) {
        $ip = getenv('REMOTE_ADDR');
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
/**
 * 字符串截取
 * @param unknown $string_input
 * @param unknown $start
 * @param unknown $length
 * @return string
 */
function substr_cn($string_input,$start,$length,$encoding = 'utf-8'){
    if(iconv_strlen($string_input,$encoding)>$length)
        return mb_substr($string_input,$start,$length,$encoding).'……';
    return $string_input;
}


